import pandas as pd
import requests
import json

# 请确保您的API Key是正确的
API_KEY = '7eecaf8606c454d7dce4eac9ae699675'

# 高德地图路径规划API URL，注意添加您的API Key和策略类型
api_url = "https://restapi.amap.com/v3/direction/driving?key={}&strategy=10".format(API_KEY)

# 读取Excel文件
df = pd.read_excel('网点汇总.xlsx')

# 存储结果的DataFrame
results_df = pd.DataFrame(columns=['起点名称', '起点坐标', '目的地', '目的地坐标', '方案数', '最短距离'])

# 遍历DataFrame中的每一行
for index, row in df.iterrows():
    try:
        # 构造请求参数
        params = {
            "origin": row['起点坐标'],
            "destination": row['目的地坐标']
        }

        # 发送请求
        response = requests.get(api_url, params=params)

        # 检查HTTP响应状态码
        if response.status_code == 200:
            result = response.json()

            # 检查API响应状态
            if result['status'] == "1" and 'paths' in result and len(result['paths']) > 0:
                path = result['route']['paths'][0]
                # 存储结果
                results_df = results_df.append({
                    '起点名称': row['起点名称'],
                    '起点坐标': row['起点坐标'],
                    '目的地': row['目的地'],
                    '目的地坐标': row['目的地坐标'],
                    '方案数': len(result['route']['paths']),
                    '最短距离': path['distance']
                }, ignore_index=True)
            else:
                print(f"Error processing {row['起点名称']} to {row['目的地']}: {result.get('info')}")
        else:
            print(f"HTTP请求失败，状态码：{response.status_code}")

    except requests.exceptions.RequestException as e:
        print(f"网络请求异常：{e}")

# 输出总方案数和总距离
total_plans = results_df['方案数'].sum()
total_distance = results_df['最短距离'].sum()
print(f"总方案数: {total_plans}")
print(f"总最短距离: {total_distance} 米")

# 保存结果到Excel文件
results_df.to_excel("路线规划结果.xlsx", index=False)